package store.lunangangster.nodeflow.core.component;

import com.alibaba.ttl.TransmittableThreadLocal;
import store.lunangangster.nodeflow.enums.NodeType;
import store.lunangangster.nodeflow.util.KeyGenerator;

/**
 * <h2>switch选择Node</h2>
 * <p>当一个节点的后续节点有0～2个时，可以使用{@link IfComponent}；而大于2个节点时，可以使用{@link SwitchComponent}实现
 *
 * @author cwk
 * @version 1.0
 */
public abstract class SwitchComponent extends NodeComponent {

  private static final ThreadLocal<String> SWITCH_KEY_TL = new TransmittableThreadLocal<>();

  @Override
  public void process() {
    String switchNodeId = processSwitch();
    String switchResultKey = KeyGenerator.generate(NodeType.NODE_SWITCH);
    SWITCH_KEY_TL.set(switchResultKey);
    this.getSlot().setData(switchResultKey, switchNodeId);
  }

  /**
   * 后续节点的选择逻辑
   * @return  被选择节点的nodeId
   */
  public abstract String processSwitch();

  @Override
  public String getSwitchResultKey() {
    return SWITCH_KEY_TL.get();
  }

  @Override
  public void removeSwitchResultKey() {
    SWITCH_KEY_TL.remove();
  }
}
